#include "ThreadPool.h"

int getsTextFunc(const char* arg, int retM,int netfd ){//输入差一个栈参数，后面可以补上
    char real_path[4096] = {0};

    off_t offset = 0;
    recvn(netfd, &offset, sizeof(off_t));
    int fd = open(arg, O_RDWR);//open第一个参数为绝对地址
    if(retM==-1 || fd==-1){
        //tran_t errorMsg;
        //bzero(&errorMsg, sizeof(tran_t));
        //strcpy(errorMsg.data, "file not exist\n");
        //errorMsg.length = strlen(errorMsg.data);
        printf("文件错误\n");
        send(netfd, &fd, sizeof(int),MSG_NOSIGNAL);
        //send(netfd, &errorMsg, sizeof(int) + errorMsg.length, MSG_NOSIGNAL);
        close(fd);
        return -1;//返回错误类型为未打开文件
    }else{
        int ret = 0;
        send(netfd, &ret, sizeof(int), MSG_NOSIGNAL);
    }
    printf("可以给客户端下载\n");
    struct stat statbuf;
    fstat(fd,&statbuf);
    //train.length=sizeof(statbuf.st_size);
    //memcpy(train.data,&statbuf.st_size,train.length);
    //send(netfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);

    train_t train;
    bzero(&train, sizeof(train));

    if(statbuf.st_size > 1000000)
	{
        //int offset = train.offset;
		char *p = (char *)mmap(NULL,statbuf.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
		if(p==(void*)-1){
            error(1,errno,"mmap is error\n");
        }
        printf("mmap 分配没出错\n");
		off_t totalsize = offset;
		while(totalsize < statbuf.st_size)
		{
			if(statbuf.st_size - totalsize > (off_t)sizeof(train.data))
				train.length = 4096;
			else
				train.length = statbuf.st_size - totalsize;
            printf("开始发送 大小为：%d\n",train.length);
			send(netfd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
            // send(netfd,&train.offset,sizeof(train.offset),MSG_NOSIGNAL);
			send(netfd,p+totalsize,train.length,MSG_NOSIGNAL);
			totalsize += train.length;
		}
	}
	else
    {
    lseek(fd, offset,SEEK_SET);
        while(1){
            ssize_t sret=read(fd,train.data,sizeof(train.data));
            if(sret==0){
                break;
            }
            printf("发送大小：%ld\n",sret);
            train.length = sret;
            // send(netfd, &train.length, sizeof(train.length), MSG_NOSIGNAL);
            sret = send(netfd, &train, sizeof(int)+train.length,MSG_NOSIGNAL);
        }
    }
    printf("发送完毕\n");
    train.length=0;
    send(netfd,&train,sizeof(train.length),MSG_NOSIGNAL);
    close(fd);
    return 0;
}
